/* eslint-disable react/self-closing-comp */
import global from '@/utils/globalUtils';
import {
  BellOutlined,
  BookOutlined,
  HomeOutlined,
  LinkOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import ProLayout from '@ant-design/pro-layout';
import {
  Link,
  matchRoutes,
  useAccessMarkedRoutes,
  useAppData,
  useLocation,
  useNavigate,
} from '@umijs/max';
import { FloatButton } from 'antd';
import { useEffect, useMemo } from 'react';
import { getAllRoutes } from '../../config/routes';
import Exception from './Exception';
import './Layout.less';
import PageContainer from './PageContainer';
import { useModel } from '@umijs/max';
import actionsRenderFn from './ActionsRender';
import ErrorBoundary from '@/components/ErrorBoundary';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');

const IconMap: any = {
  HomeOutlined: <HomeOutlined />,
  BellOutlined: <BellOutlined />,
  SettingOutlined: <SettingOutlined />,
};

const loopMenus = (routes: any) => {
  routes.children.forEach((item: any) => {
    if (item.icon && IconMap[item.icon]) {
      item.icon = IconMap[item.icon];
    }
    if (item.children) {
      loopMenus(item);
    }
  });
};
export default () => {
  global.log('我是全局layouts。');
  const location = useLocation();
  const navigate = useNavigate();
  const { clientRoutes }: any = useAppData();
  const useUserModel = useModel('useUserModel');
  const { globalInfo, requestDictionaries, loading } = useModel('useGlobalModel');

  useEffect(() => {
    requestDictionaries();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const matchedRoute: any = useMemo(
    //@ts-ignore
    () => matchRoutes(clientRoutes, location.pathname).pop()?.route,

    // eslint-disable-next-line react-hooks/exhaustive-deps
    [location.pathname],
  );

  const [route] = useAccessMarkedRoutes(
    clientRoutes.filter((r: any) => {
      return r.path === '/' && r.children && r.children.length > 0;
    }),
  );

  loopMenus(route);

  if (!globalInfo) {
    return loading;
  }
  return (
    <ProLayout
      className="pro-layout-custom"
      route={route}
      location={location}
      title="后台管理行"
      logo="/logo.png"
      locale="zh-CN"
      onMenuHeaderClick={(e: any) => {
        e.stopPropagation();
        e.preventDefault();
        navigate('/');
      }}
      itemRender={(_route: any) => {
        // 查找路由配置里面对于路由是否
        const localRoutes: any = getAllRoutes();
        const localRoute: any = localRoutes.find((i: any) => {
          return i.path === _route.path;
        });
        const props: any = {};
        // 如果配置 component 表示有页面可以跳转
        if (localRoute.component) {
          props.to = localRoute.path;
          props.name = _route.breadcrumbName;
        } else {
          props.name = _route.breadcrumbName;
        }

        return props.to ? <Link to={props.to}>{props.name}</Link> : <span>{props.name}</span>;
      }}
      menuItemRender={(menuItemProps: any, defaultDom: any) => {
        if (menuItemProps.isUrl || menuItemProps.children) {
          return defaultDom;
        }
        if (menuItemProps.path && location.pathname !== menuItemProps.path) {
          return (
            // handle wildcard route path, for example /slave/* from qiankun
            <Link to={menuItemProps.path.replace('/*', '')} target={menuItemProps.target}>
              {defaultDom}
            </Link>
          );
        }
        return defaultDom;
      }}
      onError={(err: any) => {
        global.log(err);
      }}
      siderWidth={256}
      fixSiderbar
      fixedHeader
      layout="side"
      navTheme="light"
      actionsRender={(props: any) => actionsRenderFn(props, useUserModel)}
      // rightContentRender={(props: any) => actionsRenderFn(props, useUserModel)}
      token={{
        header: {
          colorBgHeader: '#fff',
        },
        sider: {
          colorMenuBackground: '#fff',
        },
        pageContainer: {
          marginBlockPageContainerContent: 12,
          marginInlinePageContainerContent: 12,
        },
      }}
      footerRender={false}
      breadcrumbRender={false}
      links={
        process.env.UMI_ENV === 'local'
          ? [
              <a
                key="docs"
                href="https://js-veryhappy.gitee.io/vh-admin"
                target="_blank"
                rel="noreferrer"
              >
                <BookOutlined />
                <span>业务组件文档</span>
              </a>,
              <a key="openapi" href="http://" target="_blank" rel="noreferrer">
                <LinkOutlined />
                <span>openAPI 文档</span>
              </a>,
            ]
          : []
      }
      bgLayoutImgList={[
        {
          src: 'https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png',
          left: 85,
          bottom: 100,
          height: '303px',
        },
        {
          src: 'https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png',
          bottom: -68,
          right: -45,
          height: '303px',
        },
        {
          src: 'https://img.alicdn.com/imgextra/i3/O1CN018NxReL1shX85Yz6Cx_!!6000000005798-2-tps-884-496.png',
          bottom: 0,
          left: 0,
          width: '331px',
        },
      ]}
      ErrorBoundary={ErrorBoundary}
    >
      <Exception route={matchedRoute}>
        <PageContainer />
        <FloatButton.BackTop />
      </Exception>
    </ProLayout>
  );
};
